import json
import os
from datetime import datetime

class ConfigManager:
    """
    配置文件管理类
    负责读取和写入配置文件，提供默认配置
    """
    
    # 默认配置
    DEFAULT_CONFIG = {
        "general": {
            "capture_interval": 1.0,
            "model_dir": "models",
            "window_password": "681298"
        },
        "interface": {
            "right_section_width": 350,
            "camera_frame_width": 400,
            "camera_frame_height": 240,
            "logo_width": 120,
            "logo_height": 48,
            "log_text_height": 10,
            "log_font": "Courier New",
            "log_font_size": 8,
            "status_font": "Arial",
            "status_font_size": 9
        },
        "decoding": {
            "default_total_chunks": 100,
            "chunks_per_task": 5,
            "task_switch_interval": 30,
            "camera_id": 0
        },
        "work_time": {
            "enabled": False,
            "start_time": "08:00",
            "end_time": "18:00"
        },
        "alerts": {
            "no_scan_days_threshold": 1
        },
        "database": {
            "connection_timeout_ms": 5000,
            "auto_delete_existing": False
        }
    }
    
    # 配置文件路径
    CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
    
    @classmethod
    def get_config(cls):
        """
        获取配置
        如果配置文件不存在，创建默认配置文件并返回默认配置
        """
        # 检查配置文件是否存在
        if not os.path.exists(cls.CONFIG_FILE):
            cls._create_default_config()
            return cls.DEFAULT_CONFIG.copy()
        
        # 读取配置文件
        try:
            with open(cls.CONFIG_FILE, 'r', encoding='utf-8') as f:
                config = json.load(f)
                
                # 递归合并配置，确保所有必要的键都存在
                merged_config = cls._deep_merge_dicts(cls.DEFAULT_CONFIG.copy(), config)
                return merged_config
        except (json.JSONDecodeError, IOError) as e:
            print(f"读取配置文件时出错: {e}")
            print("使用默认配置")
            return cls.DEFAULT_CONFIG.copy()
    
    @staticmethod
    def _deep_merge_dicts(original, update):
        """
        递归合并两个字典
        """
        for key, value in update.items():
            if key in original and isinstance(original[key], dict) and isinstance(value, dict):
                original[key] = ConfigManager._deep_merge_dicts(original[key], value)
            else:
                original[key] = value
        return original
    
    @classmethod
    def _create_default_config(cls):
        """
        创建默认配置文件
        """
        try:
            # 确保目录存在
            os.makedirs(os.path.dirname(cls.CONFIG_FILE), exist_ok=True)
            
            # 写入默认配置
            with open(cls.CONFIG_FILE, 'w', encoding='utf-8') as f:
                json.dump(cls.DEFAULT_CONFIG, f, indent=4, ensure_ascii=False)
            
            print(f"已创建默认配置文件: {cls.CONFIG_FILE}")
        except IOError as e:
            print(f"创建默认配置文件时出错: {e}")
    
    @classmethod
    def get_general_config(cls):
        """
        获取通用配置
        """
        config = cls.get_config()
        return config.get("general", cls.DEFAULT_CONFIG["general"])
    
    @classmethod
    def get_interface_config(cls):
        """
        获取界面配置
        """
        config = cls.get_config()
        return config.get("interface", cls.DEFAULT_CONFIG["interface"])
    
    @classmethod
    def get_decoding_config(cls):
        """
        获取解码配置
        """
        config = cls.get_config()
        return config.get("decoding", cls.DEFAULT_CONFIG["decoding"])
    
    @classmethod
    def get_work_time_config(cls):
        """
        获取工作时间配置
        """
        config = cls.get_config()
        return config.get("work_time", cls.DEFAULT_CONFIG["work_time"])
    
    @classmethod
    def get_alerts_config(cls):
        """
        获取告警配置
        """
        config = cls.get_config()
        return config.get("alerts", cls.DEFAULT_CONFIG["alerts"])
    
    @classmethod
    def get_database_config(cls):
        """
        获取数据库配置
        """
        config = cls.get_config()
        return config.get("database", cls.DEFAULT_CONFIG["database"])
    
    @classmethod
    def get_capture_interval(cls):
        """
        获取扫码频率
        """
        general_config = cls.get_general_config()
        interval = general_config.get("capture_interval", 1.0)
        
        # 验证频率值是否有效
        if isinstance(interval, (int, float)) and 0 < interval <= 10.0:
            return interval
        return 1.0  # 默认值
    
    @classmethod
    def get_work_time_settings(cls):
        """
        获取工作时间设置
        返回: (enabled, start_time, end_time)
        """
        work_time_config = cls.get_work_time_config()
        enabled = work_time_config.get("enabled", False)
        start_time = work_time_config.get("start_time", "08:00")
        end_time = work_time_config.get("end_time", "18:00")
        
        return enabled, start_time, end_time
    
    @classmethod
    def get_window_password(cls):
        """
        获取窗口密码
        """
        general_config = cls.get_general_config()
        return general_config.get("window_password", "681298")
    
    @classmethod
    def get_model_dir(cls):
        """
        获取模型目录
        """
        general_config = cls.get_general_config()
        return general_config.get("model_dir", "models")
    
    @classmethod
    def parse_time_string(cls, time_str):
        """
        解析时间字符串为小时和分钟
        返回: (hour, minute) 元组，如果解析失败返回None
        """
        try:
            hour, minute = map(int, time_str.split(":"))
            if 0 <= hour <= 23 and 0 <= minute <= 59:
                return (hour, minute)
            return None
        except (ValueError, AttributeError):
            return None